package com.yonyou.brigade.basic_init.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.dao.DeveloperMapper;
import com.yonyou.brigade.basic_init.model.Developer;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kangfw5@yonyou.com
 * @since 2018-09-19
 */
@Service
public class DeveloperServiceImpl extends ServiceImpl<DeveloperMapper, Developer> implements IDeveloperService {

    private static Logger logger = LoggerFactory.getLogger(DeveloperServiceImpl.class);

    @Autowired
    private DeveloperMapper developerMapper;

    @Autowired
    private IMailService mailService;

    /**
     * 查询对应类型人员的邮箱
     *
     * @param type 类型 KF:开发 YY:运营 YW:运维 CP:产品 CS:测试 JL:经理
     * @return 邮箱列表
     */
    @Override
    public List<String> listEmailByType(String type) {
        return developerMapper.selectMailByType(type);
    }

    @Override
    public void sendEmailToDev(String curEnv, String channel, String operateType, Exception e) {
        Wrapper<Developer> developerWrapper = new EntityWrapper<>();
        developerWrapper.where("type={0}", "KF");
        List<Developer> developers = developerMapper.selectList(developerWrapper);
        String developerEmails = "";
        for (int j = 0; j < developers.size(); j++) {
            developerEmails += developers.get(j).getEmail();
            if (j < developers.size() - 1) {
                developerEmails += ",";
            }
        }
        Email email = new Email();
        String[] emails = developerEmails.split(",");
        email.setEmail(emails);
        email.setSubject(curEnv + "环境" + channel + operateType + "失败");
        email.setContent(e.getMessage());
        try {
            logger.error(e.getMessage());
            mailService.send(email);
        } catch (Exception e1) {
            logger.error("提示" + curEnv + "环境" + channel + operateType + "失败的邮件发送失败！" + e1.getMessage());
        }
    }
}
